﻿using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore.Metadata;

namespace TodoApp.EntityFrameworkCore.Core
{
    public class ModelSoftDeleteCustomizer : IMyModelCustomizer
    {
        public void Configure(IMutableEntityType entityType)
        {
            if (typeof(ISoftDelete).IsAssignableFrom(entityType.ClrType))
            {
                // Todo entityType.ClrType
                //var getExpressionMethodInfo = GetType().GetMethods(BindingFlags.NonPublic | BindingFlags.Static)
                //    .FirstOrDefault(t => t.Name == nameof(GetSoftDeleteExpression));
                // var genericGetExpressionMethod = getExpressionMethodInfo.MakeGenericMethod(entityType.ClrType);
                // var expression = (LambdaExpression)genericGetExpressionMethod.Invoke(null, null);

                var t = Expression.Parameter(entityType.ClrType);

                var expression = Expression.Lambda(
                    Expression.Equal(
                        left: Expression.Property(t, nameof(ISoftDelete.IsDeleted)),
                        right: Expression.Constant(false)
                    ), t);
                entityType.SetQueryFilter(expression);
            }
        }
        // private static Expression<Func<TEntity, bool>> GetSoftDeleteExpression<TEntity>() where TEntity : class, ISoftDelete        => t => t.IsDeleted == false;
    }
}
